package Client.TaggingSystem
import org.hibernate.cfg.Configuration
import org.hibernate.SessionFactory
import org.hibernate.Session

/**
 * Object responsible to manage the tag database
 */
object DataBase {
  
  /**
   * Save a pair of a file and a tag in the database
   * @param file the file path
   * @param tag the tag
   */
  def saveTag (file:String, tag:String){
    val cfg = new Configuration()
    var sessionFactory = null.asInstanceOf[SessionFactory]
    var session = null.asInstanceOf[Session]
    try{
      sessionFactory = cfg.configure().buildSessionFactory()
      session = sessionFactory.openSession()
      var tdbm=new TagDBManager(session)
      var t=new Tag
      t.setFile(file)
      t.setTag(tag)
      //insert the tag into the database
      tdbm.saveTag(t)
    }
    catch {
      case (e:Exception) => System.err.println(e.getMessage)
    }
  }
  
  def delete (file:String){
    val cfg = new Configuration()
    var sessionFactory = null.asInstanceOf[SessionFactory]
    var session = null.asInstanceOf[Session]
    try{
      sessionFactory = cfg.configure().buildSessionFactory()
      session = sessionFactory.openSession()
      //check if the new file exists on the DB
      var query = session.createQuery("from Tags t where t.file = " + file)
      var tdbm=new TagDBManager(session)
      for (t <- query.list.toArray)
        tdbm.deleteTag(t.asInstanceOf[Tag])
    }
    catch {
      case e:Exception => System.err.println(e.getMessage)
    }
  }
}